package com.atjinggu.jinggumail.seckill.config;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author jingming
 * @Type CustomRabbitConfig.java
 * @Desc
 * @date 2021/3/7 0:56
 */
@Configuration
public class CustomRabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }


    /**
     * 确认消息抵达broker
     */
    @PostConstruct  //CustomRabbitConfig构造完成后，执行该方法
    public void initRabbitTemplate(){
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             * 只要消息抵达broker ack就为true
             * @param correlationData 消息的唯一标识
             * @param ack  消息是否抵达broker
             * @param cause ack为false时，失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("消息已到达broker！");
            }
        });

        /**
         * 当消息投递给queue失败时，回调函数
         */
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             *
             * @param message  当前消息内容
             * @param replyCode 返回状态码
             * @param replyText 返回错误提示
             * @param exchange  发送的交换机
             * @param routingKey 发送时指定的路由建
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                System.out.println("消息投递给queue失败！");
            }
        });

    }
}